<?php
/**
 * Created by PhpStorm.
 * User: MrHung
 * Date: 1/22/14
 * Time: 5:50 PM
 */

namespace Frontend\Controller;

use Admin\Model\AdminTopic;
use Admin\Model\AdminTopicImg;
use Admin\Model\AdminUserTable;
use Frontend\Form\addTopicForm;
use Zend\Authentication\AuthenticationService;
use Zend\Log\Writer\Null;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Admin\Model\AdminUser;
use \Velacolib\Utility\Utility;
use Zend\Form\Element;
use Frontend\Helper\recaptchalib;

class RegisterController extends AbstractActionController {

    protected $topicModel;
    protected $topicImg;
    public function onDispatch(\Zend\Mvc\MvcEvent $e)
    {
        $this->topicModel = Utility::UserGateway('Admin\Model\AdminTopicTable');
        $this->topicImg = Utility::UserGateway('Admin\Model\AdminTopicImgTable');

        $this->layout('frontend/layout');
        return parent::onDispatch($e);
    }
    public function indexAction(){

    }
    public function registerAction()
    {
        $response['result'] = false;
        $response['register'] = false;
        $response['user_id'] = null;
        $response['redirect'] = false;

        //Ajax function
        if ($this->getRequest()->isPost()) {

            $dataSubmit = $this->params()->fromPost();

            //Check if ajax request is submited
            if($dataSubmit['password'] != $dataSubmit['confirm_password']){
                $response['result'] = false;
                $response['message'] = 'Nhập lại mật khẩu không đúng';
                echo json_encode($response);die;
            }




                $user_model = new AdminUser();

                $dataSubmit['name'] = $this->params()->fromPost('name');

                $dataSubmit['status'] = '1';

                $dataSubmit['user_type'] = '2';

                $time = time();

                $dataSubmit['time_reg'] = $time;
                $password = $dataSubmit['password'];
                $dataSubmit['avatar'] = '/img/upload/user_temp/person-avatar.png';

                $dataSubmit['password'] = md5($dataSubmit['email'] . $dataSubmit['password']);


                unset ($dataSubmit['firstname'], $dataSubmit['lastname'], $dataSubmit['confirm_password']);

                $object = Utility::UserGateway('Admin\Model\AdminUserTable')->getUserByEmail($dataSubmit['email']);


                if (is_object($object)) {

                    $response['result'] = false;

                    $response['message'] = 'Email này đã có người sử dụng';

                } else {
                    $array_contact = array();
                    if(isset($dataSubmit['contact'])){
                        $array_contact = $dataSubmit['contact'];
                        unset($dataSubmit['contact']);
                    }

                    $user_model->exchangeArray($dataSubmit);
                    $addUser = Utility::UserGateway('Admin\Model\AdminUserTable')->saveUser($user_model);

                    $user_table = Utility::UserGateway('Admin\Model\AdminUserTable');
                    $data['username'] = $dataSubmit['email'];
                    $data['password'] =    $password;

                    if ($addUser) {
                        foreach($array_contact as $key => $values){

                            foreach($values as $value){
                                $adminuserContact = new AdminUserContact();
                                $adminuserContact->user_id = $addUser;
                                $adminuserContact->contact_type = $key;
                                $adminuserContact->contact_value = $value;
                                Utility::UserGateway('Admin\Model\AdminUserContactTable')->saveUserContact($adminuserContact);
                            }
                        }

                        $user_table->setLoginUser($data);
                        $login_obj = new AuthenticationService(null, $user_table)   ;
                        $login_obj->authenticate();


                        $response['result'] = true;


                        $response['message'] = 'Đăng ký thành công!';
                        $response['register'] = true;
                        $response['user_id'] =   Utility::UserGateway('Admin\Model\AdminUserTable')->getLastIdInsert();
                        $response['redirect'] = true;
                        $response['url'] = '/';
                        //sending email verify to user register
                        $smtp_option = null;
                        $senderInfo = array(
                            'email' => 'mrhungmaster1905@gmail.com',
                            'name' => 'VelaCo'

                        );

                        $RecipientInfo = array(
                            'email' => $dataSubmit['email'],
                            'name' => $dataSubmit['name'],
                            'link' => 'http://' . $_SERVER['HTTP_HOST'] . '/user/verify/' . $time,
                        );

                        $template_path = 'admin/email/tpl/template';

                        $subject = 'Email Verify';

                        Utility::SendMail(false, $smtp_option = null, $senderInfo, $RecipientInfo, $template_path, $subject);

                    } else $response['message'] = 'Không thể đăng ký người dùng mới';
                }


        } else $response['message'] = 'Method not allowed';
       // header("ContentType: application/json");
        echo json_encode($response);
        die();
    }

    public function userimagesAction(){
        $result['upload'] = "0";
        $file_type = $_FILES['file']['type'];
        if (!strstr ($file_type, 'image'))
            $result['message'] = 'Định dạng không đúng, chỉ chấp nhận file ảnh!';
        else{
            $target = $_SERVER['DOCUMENT_ROOT'] . '/img/upload/user_temp/' . $_FILES['file']['name'];
            $upload = move_uploaded_file($_FILES['file']['tmp_name'], $target);
            if ($upload){
                $imageUrl = '/img/upload/user_temp/' . $_FILES['file']['name'];
                $result['upload'] = "1";
                $result['img_url'] = $imageUrl;
                $result['message'] = 'Upload thành công';
            }
            else $result['message'] = 'Có lỗi trong quá trình xử lý, xin vui lòng thử lại';
        }
        header ('ContentType: application/json');
        echo json_encode($result);
        die();
    }

    public function addtopicAction(){
        $return = '' ;
        $template_default = 'frontend/register/addtopic.phtml';
        $template_step2 = 'frontend/register/topicStep2.phtml';
        if($this->getRequest()->isPost()){
            $return = $this->params()->fromPost();
            $template = $template_step2;
        }else{
            $template = $template_default;
        }



        $view =  new ViewModel(array(
            'data'=>$return
        ));
        $view->setTemplate($template);
        return $view;
    }


    public function addtopic2Action(){
        $gel = array();
        $mess = '';
        // add topic with method  no account
        if(isset($_POST) && $_POST['submit']== 'Register'){
            $data_reg = $this->params()->fromPost();
            if(!isset($data_reg['password'])) $data_reg['password'] = null;
            if($data_reg['password'] != null) $data_reg['password'] = md5($data_reg['email'].$data_reg['password']);
            $user = array(
                'name' => $data_reg['f_name'].' '.$data_reg['l_name'],
                'email' => $data_reg['email'],
                'address' => $data_reg['address'],
                'phone' => $data_reg['phone'],
                'password' => $data_reg['password'],
            );
            $login['username'] = $user['email'];
            $login['password'] = $data_reg['password'];
            $object = Utility::UserGateway('Admin\Model\AdminUserTable')->getUserByEmail($user['email']);

            if(!is_object($object)){
                if(isset($data_reg['geltotal'])){
                    for($i = 0; $i< (int) $data_reg['geltotal'];$i++){
                        $gel[] = $data_reg['gel'.$i];
                        unset($data_reg['gel'.$i]);
                    }
                    unset($data_reg['geltotal']);
                }
                //destroy data unused
                unset($data_reg['submit']);
                unset($data_reg['f_name']);
                unset($data_reg['l_name']);
                unset($data_reg['email']);
                unset($data_reg['address']);
                unset($data_reg['phone']);
                unset($data_reg['password']);
                unset($data_reg['r_password']);

                 $user_model = new AdminUser();
                $user_model->exchangeArray($user);

                $user_id = Utility::UserGateway('Admin\Model\AdminUserTable')->saveUser($user_model);

                    $user_table = Utility::UserGateway('Admin\Model\AdminUserTable');

                    $user_table->setLoginUser($login);

                    $login_obj = new AuthenticationService(null, $user_table);

                    $login_obj->authenticate();

                // add topic
                $topic = new AdminTopic();
                if(count($gel)>0){
                    $gallery = $gel;
                }
                $data_reg['user_id'] = $user_id;
                $data_reg['status'] = 2;
                $data_reg['create_date'] = date("Y-m-d H:i:s");
                $data_reg['thumb'] = str_replace("/img/upload/","/img/upload/thumb/",$data_reg['images']);
                 //print_r($data_reg);die;
                $topic->exchangeArray($data_reg);
                $topic_id = $this->topicModel->saveTopic($topic);

                if(isset($gallery)){
                    foreach($gallery as $g){
                        $data_gallery = array(
                            'topic_id' => $topic_id,
                            'link' => str_replace("/img/upload/","/img/upload/",$g),
                            'user_id' => $user_id
                        );
                        $topicImgModel = new AdminTopicImg();
                        $topicImgModel->exchangeArray($data_gallery);

                        $this->topicImg->saveTopicImg($topicImgModel);
                    }
                }


                $this->flashMessenger()->addSuccessMessage("Đăng tin thành công");
                $this->redirect()->toRoute('frontendtopic',array(
                    'action'=>'detail',
                    'id'=>$topic_id
                ));
            }else{
                unset($data_reg['f_name']);
                unset($data_reg['l_name']);
                unset($data_reg['email']);
                unset($data_reg['address']);
                unset($data_reg['phone']);
                unset($data_reg['password']);
                unset($data_reg['r_password']);
                $mess = "Email has been already exits";
                $view = new ViewModel(array(
                   'data'=>$data_reg ,
                    'hide'=>1,
                    'error' => true,
                    'mess'=>$mess
                ));
                return $view->setTemplate('frontend/register/topicStep2.phtml');
            }
        }


        // add topic with method  acccount
        if(isset($_POST) && $_POST['submit']== 'Login'){
            $data_log = $this->params()->fromPost();
            $user['username'] = $data_log['username_log'];
            $user['password'] = $data_log['password_log'];

            unset($data_log['submit']);
            unset($data_log['username_log']);
            unset($data_log['password_log']);

            $user_table = Utility::UserGateway('Admin\Model\AdminUserTable');
            $user_table->setLoginUser($user);
            $login_obj = new AuthenticationService(null, $user_table);

            $login_obj->authenticate();

            if ($login_obj->hasIdentity() == 1) {
                if(isset($data_log['geltotal'])){
                    for($i = 0; $i< (int) $data_log['geltotal'];$i++){
                        $gel[] = $data_log['gel'.$i];
                        unset($data_log['gel'.$i]);
                    }
                    unset($data_log['geltotal']);
                }
                $topic = new AdminTopic();
                if(count($gel)>0){
                    $gallery = $gel;
                }
                $data_log['user_id'] = $login_obj->getIdentity()->userid;
                $data_log['status'] = 2;
                $data_log['create_date'] = date("Y-m-d H:i:s");

                $data_log['thumb'] = str_replace("/img/upload/","/img/upload/",$data_log['images']);

                //echo '<pre>';
               // print_r($data_log);die;
                $topic->exchangeArray($data_log);
               $topic_id = $this->topicModel->saveTopic($topic);

                if(isset($gallery)){
                    foreach($gallery as $g){
                        $data_gallery = array(
                            'topic_id' => $topic_id,
                            'link' => str_replace("/img/upload/","/img/upload/",$g),
                            'user_id' => $login_obj->getIdentity()->userid
                        );
                        $topicImgModel = new AdminTopicImg();
                        $topicImgModel->exchangeArray($data_gallery);

                        $this->topicImg->saveTopicImg($topicImgModel);
                    }
                }

                $this->flashMessenger()->addSuccessMessage("Đăng tin thành công");
                $this->redirect()->toRoute('frontendtopic',array(
                    'action'=>'detail',
                    'id'=>$topic_id
                ));

            }else{
                $mess = ' Wrong username or password!';

                $view = new ViewModel(array(
                   'data'=>$data_log,
                    'error' => true,
                    'mess'=>$mess
                ));
                $view->setTemplate('frontend/register/topicStep2.phtml');
                return $view;
            }

        }
    }

}